package com.mate.cloud.auth.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 记录登录失败日志
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/6/6 11:21
 * @updateUser: MI
 * @updateTime: 2025/6/6 11:21
 * @updateRemark: 修改内容
 * @version: 1.0
 */
@Slf4j
@Component
public class LoggingAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String username = request.getParameter("username");
        String ipAddress = request.getRemoteAddr(); // IP地址
        LocalDateTime loginTime = LocalDateTime.now(); // 时间

        // 记录详细的登录失败日志
        log.warn("登录失败 - 用户名: {}, IP地址: {}, 时间: {}, 原因: {}",
                username, ipAddress, loginTime, exception.getMessage());

        // 其他处理逻辑...
        response.sendRedirect(request.getContextPath() + "/login?error");
    }
}
